import "dotenv/config";
{{#if (eq api "trpc")}}
import { createExpressMiddleware } from "@trpc/server/adapters/express";
import { createContext } from "@{{projectName}}/api/context";
import { appRouter } from "@{{projectName}}/api/routers/index";
{{/if}}
{{#if (eq api "orpc")}}
import { OpenAPIHandler } from "@orpc/openapi/node";
import { OpenAPIReferencePlugin } from "@orpc/openapi/plugins";
import { ZodToJsonSchemaConverter } from "@orpc/zod/zod4";
import { RPCHandler } from "@orpc/server/node";
import { onError } from "@orpc/server";
import { appRouter } from "@{{projectName}}/api/routers/index";
{{#if (eq auth "better-auth")}}
import { createContext } from "@{{projectName}}/api/context";
{{/if}}
{{/if}}
import cors from "cors";
import express from "express";
{{#if (includes examples "ai")}}
import { streamText, type UIMessage, convertToModelMessages } from "ai";
import { google } from "@ai-sdk/google";
{{/if}}
{{#if (eq auth "better-auth")}}
import { auth } from "@{{projectName}}/auth";
import { toNodeHandler } from "better-auth/node";
{{/if}}

const app = express();

app.use(
  cors({
    origin: process.env.CORS_ORIGIN || "",
    methods: ["GET", "POST", "OPTIONS"],
    {{#if (eq auth "better-auth")}}
    allowedHeaders: ["Content-Type", "Authorization"],
    credentials: true,
    {{/if}}
  })
);

{{#if (eq auth "better-auth")}}
app.all("/api/auth{/*path}", toNodeHandler(auth));
{{/if}}

{{#if (eq api "trpc")}}
app.use(
  "/trpc",
  createExpressMiddleware({
    router: appRouter,
    createContext,
  })
);
{{/if}}

{{#if (eq api "orpc")}}
const rpcHandler = new RPCHandler(appRouter, {
  interceptors: [
    onError((error) => {
      console.error(error);
    }),
  ],
});
const apiHandler = new OpenAPIHandler(appRouter, {
  plugins: [
    new OpenAPIReferencePlugin({
      schemaConverters: [new ZodToJsonSchemaConverter()],
    }),
  ],
  interceptors: [
    onError((error) => {
      console.error(error);
    }),
  ],
});

app.use(async (req, res, next) => {
  const rpcResult = await rpcHandler.handle(req, res, {
    prefix: "/rpc",
    {{#if (eq auth "better-auth")}}
    context: await createContext({ req }),
    {{else}}
    context: {},
    {{/if}}
  });
  if (rpcResult.matched) return;

  const apiResult = await apiHandler.handle(req, res, {
    prefix: "/api-reference",
    {{#if (eq auth "better-auth")}}
    context: await createContext({ req }),
    {{else}}
    context: {},
    {{/if}}
  });
  if (apiResult.matched) return;

  next();
});
{{/if}}

app.use(express.json());

{{#if (includes examples "ai")}}
app.post("/ai", async (req, res) => {
  const { messages = [] } = (req.body || {}) as { messages: UIMessage[] };
  const result = streamText({
    model: google("gemini-2.5-flash"),
    messages: convertToModelMessages(messages),
  });
  result.pipeUIMessageStreamToResponse(res);
});
{{/if}}

app.get("/", (_req, res) => {
  res.status(200).send("OK");
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
